const http = require('http')
const fs = require('fs')
const S = require('string')

const url = "http://www.51ape.com/artist/"

// 更新歌手列表页面信息
module.exports.updateSingerList = function () {
    http.get(url, res => {
        console.log(res.statusCode)
        if (res.statusCode === 200) {
            var html = ''
            res.on('data', data => {
                html += data
                if (html.indexOf('<!--Z end-->') !== -1) {
                    res.destroy()
                }
            })

            res.on('end', () => {
                let result = html.match(/(?<=gs_a"\>).{0,150}(?=\<\/a\>)/g).map(v => {
                    let url = S(v).between(`href="`, `" class`).s,
                        singer = v.replace(/\<span\>.*\<\/span\>/g, '').match(/(?<=\>).*/g)[0], // 剔除包裹的span标签
                        hasPage = url.indexOf('http') === -1 ? false : true // 是否有单独页面
                    return {
                        url: hasPage ? url : "http://www.51ape.com/skin/ape/php/qx_2.php?qx=" + singer.replace(/\s/g, '+'),
                        singer,
                        hasPage
                    }
                })

                console.log(result.length)
                // 使用绝对路径
                fs.writeFile(__dirname + '\\..\\Data\\singerInfo.json', JSON.stringify(result), err => {
                    if (err) console.error('error')
                    console.log('歌手列表最新信息更新成功！')
                })

            })
        }

    }).on('error', err => {
        console.log('errorMessage: ' + err)
    })
}
// 绝对路径测试
module.exports.test = function () {
    fs.writeFile(__dirname + '\\..\\Data\\test.json', JSON.stringify([1, 2]), err => {
        if (err) console.log(err)
        console.log('test.json create success!')
    })
}